package com.example.shortmessage.presenter;

import android.app.Activity;

import com.example.shortmessage.contract.LoginContract;
import com.example.shortmessage.data.constant.LoginConst;
import com.example.shortmessage.data.entity.User;
import com.example.shortmessage.model.LoginModel;
import com.example.shortmessage.ui.activity.MainActivity;
import com.example.shortmessage.utils.MD5Utils;
import com.example.shortmessage.utils.SPUtils;
import com.example.shortmessage.utils.ToastUtils;

/**
 * @author 27638
 */
public class LoginPresenter extends LoginContract.Presenter<LoginContract.View> {
    private Activity activity;
    private final LoginModel model;

    public LoginPresenter(Activity activity) {
        this.activity = activity;
        model = new LoginModel();
    }

    @Override
    public String getUsername() {
        return SPUtils.getInstance(activity).getString(LoginConst.NAME);
    }

    @Override
    public String getPassword() {
        return SPUtils.getInstance(activity).getString(LoginConst.PASS_WORD);
    }

    @Override
    public void login(String username, String password) {
        mViewRef.get().showLoading();
        User user = model.query(username);
        mViewRef.get().hideLoading();
        if(user==null){
            ToastUtils.showLongToastCenter(activity, LoginConst.NOT_NULL);
            return;
        }
        if(!user.getPassword().equals(MD5Utils.md5(password))){
            ToastUtils.showLongToastCenter(activity, LoginConst.NOT_EQUAL);
            return;
        }
        mViewRef.get().showLoading();
        SPUtils.getInstance(activity).put(LoginConst.NAME,username);
        SPUtils.getInstance(activity).put(LoginConst.PASS_WORD,password);
        MainActivity.MainActivityInstance(activity);
        activity.finish();
    }

    @Override
    public void release() {

    }
}
